var util = require('../../utils/util.js');
var app = getApp();
Page({
  data: {
    //焦点图
    imgUrls: ['../../weixinImg/flbanner@2x.png', '../../weixinImg/flbanner@2x.png', '../../weixinImg/flbanner@2x.png'],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    indicatorActiveColor: '#ffffff',
    //点击下拉显示
    showView: true,
    //一级分类
    tabs: [],
    category: [],
    detail: [],
    isScroll: true,
    curIndex: -1,
    clickId: 0,
    gc_id: '',
    num: 1,
    cur_page: 1,
    page_num: 10,
    scrollLeftNumber: 0,
  },
  onLoad: function (options) {
    var that = this;
    if (app.class_id != "") {
      return;
    }
    util.postUrl(
      'goods_class/get_list', {

      },
      function (res) {
        if (res.data.code == 200) {

          // 初始化渲染分类页面
          var gc_id = res.data.datas.parent_list[0].gc_id
6
          //获取右边的列表
          that.getList(gc_id);
          that.setData({
            tabs: res.data.datas.parent_list,
            categoryList: res.data.datas.child_class_list,
            category: res.data.datas.child_class_list[gc_id],
            gc_id: gc_id, //下次再点击分类页面需要用
          })
        }
      })
  },
  onShow: function () {
    var that = this;
    console.log(app.class_id);
    if (app.class_id != "") {
      that.setData({
        cur_page: 1,
      })
      util.postUrl(
        'goods_class/get_list', {

        },
        function (res) {
          if (res.data.code == 200) {
            that.setData({
              tabs: res.data.datas.parent_list,
              categoryList: res.data.datas.child_class_list,
            })
            var tabs = res.data.datas.parent_list;
            console.log("tabs", tabs);
            for (let key in tabs) {
              if (tabs[key].gc_id == app.class_id.parent_id) {
                console.log("选中的key", key)
                var clickId = parseInt(key);
                that.setData({
                  clickId: clickId,
                })
                if (clickId > 3) {
                  that.setData({
                    scrollLeftNumber: clickId * 130,
                  })
                } else {
                  that.setData({
                    scrollLeftNumber: 0,
                  })
                }
                break;
              }
            }
            var category = res.data.datas.child_class_list[app.class_id.parent_id];
            if (app.class_id.gc_id == 0) {
              app.class_id.gc_id = tabs[that.data.clickId].gc_id;
              that.setData({
                curIndex: -1,
              })
            } else {
              for (let key in category) {
                if (category[key].gc_id == app.class_id.gc_id) {
                  console.log("选中的key", key)
                  that.setData({
                    curIndex: parseInt(key),
                  })
                  break;
                }
              }
            }
            that.setData({
              category: category,
              gc_id: app.class_id.gc_id,
            })
            app.class_id = "";
            that.getList(that.data.gc_id);
          }
        })
      return;
    }
    // //获取右边的列表
    if (that.data.gc_id) {
      that.getList(that.data.gc_id);
    }

  },
  // 点击大分类改变左侧边栏
  tabClick: function (e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var scrollLeftNumber = that.data.scrollLeftNumber;
    var x = e.currentTarget.offsetLeft;
    that.setData({
      scrollLeftNumber: x - 160,
    })

    var gc_id = that.data.tabs[index].gc_id;
    var category = that.data.categoryList[gc_id];
    if (category) {
      that.setData({
        clickId: index,
        category: category,
        curIndex: -1,
        gc_id: gc_id,
        cur_page: 1,
      })
    } else {
      that.setData({
        clickId: index,
        category: [],
        curIndex: -1,
        gc_id: gc_id,
        cur_page: 1,
      })
    }

    //获取右边的列表
    that.getList(gc_id);
  },
  // 左侧分类点击商品展示
  switchTab(e) {
    var that = this;
    var gc_id = e.currentTarget.dataset.id;
    that.setData({
      gc_id: gc_id,
      cur_page: 1,
      curIndex: e.currentTarget.dataset.index
    })
    that.getList(gc_id);

  },

  //点击减号
  bindMinus: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];

    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (item.num - 1 < 0) {
      return;
    }
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          if (item.num - 1 == 0) {
            temp_goods.splice(i, 1);
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
          } else {
            temp_goods[i].quantity = item.num - 1;
            temp_goods[i].goods_num = item.num - 1;
          }
        }
      }
      item.num = item.num - 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);
      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      if (item.num - 1 == 0) {
        util.postUrl("cart/cart_remove", {
          cart_id: item.goods_id,
          del_type: 2,
        }, function (res) {
          if (res) {
            if (check_list.indexOf(item.goods_id) != -1) {
              check_list.splice(check_list.indexOf(item.goods_id), 1);
            }
            wx.setStorageSync("check_list", check_list);
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          }
        })
      } else {
        util.postUrl('cart/cart_add', {
          goods_id: item.goods_id,
          quantity: item.num - 1,
        }, function (res) {
          if (res) {
            item.num = item.num - 1;
            that.setData({
              detail: temp
            });
            that.initRed();
          } else { }
        })
      }
    }
  },

  /* 点击加号 */
  bindPlus: function (e) {
    var that = this;



    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;
    var item = temp[index].spec_list[spec_index];
    item.num = parseInt(item.num);
    var check_list = wx.getStorageSync('check_list');
    if (check_list == '') {
      check_list = [];
    }

    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num + 1;
          temp_goods[i].goods_num = item.num + 1;
          flag = false;
        }
      }
      if (flag) {
        check_list.push(item.goods_id);
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num + 1,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num + 1,
          goods_price: item.goods_price,
        });
      }
      item.num = item.num + 1;
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      wx.setStorageSync('check_list', check_list);

      console.log('check_list', wx.getStorageSync('check_list'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: item.num + 1,
      }, function (res) {
        if (res) {
          if (res.data.code == 400) {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'success',
              duration: 2000
            })
            return;
          }
          if (check_list.indexOf(item.goods_id) == -1) {
            check_list.push(item.goods_id);
          }
          wx.setStorageSync('check_list', check_list);
          console.log(check_list);
          item.num = item.num + 1;
          that.setData({
            detail: temp
          });
          that.initRed();
        } else { }
      })
    }

  },
  /* 输入框事件 */
  bindManual: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var spec_index = e.currentTarget.dataset.spec_index
    var temp = that.data.detail;

    var item = temp[index].spec_list[spec_index];
    // var index = e.currentTarget.dataset.index;
    console.log(item);
    var temp_num = parseInt(item.num);
    // 将数值与状态写回
    console.log(e.detail.value)
    if (e.detail.value == '' || e.detail.value == 0) {
      e.detail.value = 1;
    }
    item.num = parseInt(e.detail.value);
    that.setData({
      detail: temp,
    })
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      if (temp_goods == '') {
        temp_goods = [];
      }
      var flag = true;
      for (var i = 0; i < temp_goods.length; i++) {
        if (temp_goods[i].goods_id == item.goods_id) {
          temp_goods[i].quantity = item.num;
          temp_goods[i].goods_num = item.num;
          flag = false;
        }
      }
      if (flag) {
        temp_goods.push({
          goods_id: item.goods_id,
          quantity: item.num,
          goods: {
            goods_id: item.goods_id,
            goods_image_url: temp[index].goods_img,
            goods_name: item.goods_name,
            goods_price: item.goods_price,
            goods_unit: temp[index].goods_unit,
          },
          goods_num: item.num,
          goods_price: item.goods_price,
        });
      }
      that.setData({
        detail: temp
      });
      wx.setStorageSync('temp_goods', temp_goods);
      console.log('temp_goods', wx.getStorageSync('temp_goods'));
      that.initRed();
    } else {
      util.postUrl('cart/cart_add', {
        goods_id: item.goods_id,
        quantity: parseInt(e.detail.value),
      }, function (res) {
        if (res.data.code == 200) {
          that.initRed();

        } else {
          wx.showToast({
            title: res.data.datas.error,
            icon: 'none'
          })
          item.num = temp_num;
          that.setData({
            detail: temp
          });
          that.initRed();
        }
      })
    }

  },
  //点击显示隐藏
  onChangeShowState: function (e) {
    var that = this;
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var temp = that.data.detail;
    if (temp[index].showView) {
      temp[index].showView = false;
    } else {
      temp[index].showView = true;
    }
    that.setData({
      detail: temp,
    })
  },
  //更新购物车气泡数
  initRed: function () {
    var that = this;
    if (wx.getStorageSync('token') == '') {
      var temp_goods = wx.getStorageSync('temp_goods');
      var sum = 0;
      if (temp_goods != '') {
        for (var i = 0; i < temp_goods.length; i++) {
          sum = sum + temp_goods[i].quantity;
        }
      }

      if (sum == 0) {
        wx.hideTabBarRedDot({
          index: 2,
        })
      } else {
        wx.setTabBarBadge({
          index: 2,
          text: sum + "",
        })
      }

    } else {
      util.postUrl('cart/cart_count', {}, function (res) {
        if (res) {
          if (res.data.datas.count.goods_total_num == 0) {
            wx.hideTabBarRedDot({
              index: 2,
            })
          } else {
            wx.setTabBarBadge({
              index: 2,
              text: (res.data.datas.count.goods_total_num + ""),
            })
          }
        }
      })
    }

  },
  getList: function (gc_id) {
    var that = this;
    util.postUrl(
      'goods/get_list', {
        gc_id: gc_id,
        cur_page: that.data.cur_page,
        page_num: that.data.page_num,
        user_city_id: app.user_city_id,
      },
      function (res) {
        if (res.data.code == 200) {

          var temp = res.data.datas.goods_list;
          if (that.data.cur_page == 1) {
            that.data.detail = [];
          }
          if (temp.length > 0) {
            that.setData({
              cur_page: parseInt(that.data.cur_page) + 1,
            })
          }

          that.initRed();
          var detail = that.data.detail;
          temp = detail.concat(temp);

          for (var i = 0; i < temp.length; i++) {
            if (temp[i].min_goods_price == temp[i].max_goods_price) {
              temp[i].price = temp[i].min_goods_price
            } else {
              temp[i].price = temp[i].min_goods_price + " - ￥" + temp[i].max_goods_price
            }
            for (var j = 0; j < temp[i].spec_list.length; j++) {
              var temp_goods = wx.getStorageSync('temp_goods');
              temp[i].spec_list[j].num = 0;
              if (wx.getStorageSync('token') == '') {
                for (var z = 0; z < temp_goods.length; z++) {
                  if (temp_goods[z].goods_id == temp[i].spec_list[j].goods_id) {
                    temp[i].spec_list[j].num = temp_goods[z].quantity;
                  }
                }
              } else {
                var member_carts = res.data.datas.member_carts;
                var num = member_carts[temp[i].spec_list[j].goods_id];
                if (num) {
                  temp[i].spec_list[j].num = num;
                }
              }
            }
          }
          that.setData({
            detail: temp,
          })
        }
      })
  },
  goSearch: function () {
    wx.navigateTo({
      url: '../search/search',
    })
  },
  goGoodsDetail: function (e) {
    var item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '../goods-details/goods-details?item=' + JSON.stringify(item),
    })
  },
  //上拉加载
  handlescrolltolower: function () {
    var that = this;
    that.getList(that.data.gc_id);
  }
})